//填充模版
function doT_render(doT_ele,doT_script,doT_data){
    // console.log(doT_data)
    var evalText = doT.template($(doT_script).text());
    // console.log(evalText)
    $(doT_ele).append(evalText(doT_data));
}

function doT_render2(doT_ele,doT_script,doT_data){
    // console.log(doT_data)
    var evalText = doT.template($(doT_script).text());
    // console.log(evalText)
    $(doT_ele).html(evalText(doT_data));
}

var response_status = {
    '200' : '操作成功',
    '500' : '操作失败',
    '201' : '用户名或密码错误',
    '400' : '非法请求参数',
    '401' : '用户未登录',
    '403' : '访问权限不足',
    '404' : '访问资源不存在'
};

function s_loading(){
    $('body').append('<div class="loading_box flex"><div class="loading_img_box flex"></div></div>');
    setTimeout(function(){ $('.loading_box').addClass('loading_box_ac')},200)
}

function h_loading(){
    // setTimeout(function () {
        $('.loading_box').remove();
    // },300)
    // $('.loading_box').removeClass('loading_box_ac');
}


function s_warning(text){
    $('body').append('<div class="warning flex">'+text+'</div>');
    setTimeout(function(){ $('.warning').addClass('warning_ac');
        setTimeout(function () {
            setTimeout(function () {
                $('.warning').remove();
            },1000)
            $('.warning').removeClass('warning_ac');
        },1000)

    },200)
}

function jq_post(url,data,fn){
    s_loading()
    $.ajax({
        type: "POST",
        url: url,
        data: data,
        xhrFields: {
            withCredentials: true // 这里设置了withCredentials
        },
        success: function(result) {
            h_loading()
            if(result.code == 200){
                fn(result.data)
            }
            else if(result.code==401){
                url_jump('login')
            }else if(result.code==403){
                url_jump('power')
            }else{
                fn(result)
                s_warning(response_status[result.code])
            }
        },
        error: function(error) {
            h_loading()
            s_warning('请求错误')
        }
    });
}

function jq_get(url,fn){
    s_loading()
    $.ajax({
        type: "GET",
        url: url,
        xhrFields: {
            withCredentials: true // 这里设置了withCredentials
        },
        success: function(result) {
            h_loading()
            if(result.code == 200){
                fn(result.data)
            }
            else if(result.code==401){
                url_jump('login')
            }else if(result.code==403){
                url_jump('power')
            }else{
                s_warning(response_status[result.code])
            }
        },
        error: function(error) {
            h_loading()
            s_warning('请求错误')
        }
    });
}

function url_jump(page, data) {
    var str = '';
    var str_arr = []
    if(data){
        for(var i in data){
            if(data[i]==""){
                str_arr.push(i+'=null')
            }else{
                str_arr.push(i+'='+data[i])
            }

        }
        str = '?'+str_arr.join('&')
        window.location.href = page+'.html'+str;
    }else{
        window.location.href = page+'.html';

    }

}

function set_storage(data){
    for(var i in data){
        localStorage[i] = data[i]
    }
}

function get_storage(storage_name){
    return localStorage[storage_name]
}

$('.quit_btn').on('click',function () {
    jq_get(ajax_url.logout,function (res) {
        // console.log(res)
        url_jump('login')
    })
})

function render_user(){
    var userinfo = JSON.parse(get_storage('userInfo'));
    if(userinfo){
        if(userinfo!=""&&userinfo.avatar){
            $('.photo').css({
                "background" : "url("+userinfo.avatar+")",
                "background-size" : "cover"
            });
        }
        $('.name').text(userinfo.loginName)
    }
    else{
        url_jump('login')
    }

}

function arr_remove(arr,val){
    var index = arr.indexOf(val);
    if (index > -1) {
        return arr.splice(index, 1);
    }else{
        return false
    }
}

function downfile(x){
    // jq_post(ajax_url.downloadDocZip,{"ids":'fc4984ebe5d24b7fb80e17d1eceafa90'},function (res) {})
    var $form = $("<form action="+ajax_url.downloadDocZip+" id='download' class='hidden' method='post'></form>");
    $('body').append($form);
    var $input1 = $("<input name='ids' type='text'/>");
    $input1.attr("value",x);
    $("#download").append($input1);
    $form.submit();
    $form.remove();
}

function saveCollect(x,fn){
    jq_post(ajax_url.saveCollect,{"docId":x},function (res) {
        fn()
    })
}

function cancelCollect(x,fn){
    jq_post(ajax_url.cancelCollect,{"docId":x},function (res) {
        fn()
    })
}

function paging_render(y,x){

    var prve='',next='',str = '',total_num='';
    total_num = '<span class="paging_total">共'+x.total+'条</span>';
    if(x.pageNo==1){
        prve = '<div pageno="null">上一页</div>';
        next = '<div class="can_click" pageno="'+(x.pageNo+1)+'">下一页</div>';
    }else if(x.pageNo==x.totalPage){
        prve = '<div class="can_click" pageno="'+(x.pageNo-1)+'">上一页</div>';
        next = '<div pageno="null">下一页</div>';
    }else{
        prve = '<div class="can_click" pageno="'+(x.pageNo-1)+'">上一页</div>';
        next = '<div class="can_click" pageno="'+(x.pageNo+1)+'">下一页</div>';
    }
    if(x.totalPage<7){
        for(var i=0;i<x.totalPage;i++){
            x.pageNo==(i+1)?str+='<div pageno="'+(i+1)+'" style="color:#1772fa">'+(i+1)+'</div>':str+='<div pageno="'+(i+1)+'">'+(i+1)+'</div>'
        }
    }else{
        if(x.pageNo>3&&x.pageNo<x.totalPage-2){
            str = '<div pageno="1">1</div>'+
                '<div pageno="2">2</div>'+
                '<div pageno="3">3</div>'+
                '<div pageno="null">...</div>'+
                '<div pageno="'+x.pageNo+'" style="color: #1772fa">'+x.pageNo+'</div>'+
                '<div pageno="null">...</div>'+
                '<div pageno="'+(x.totalPage-2)+'">'+(x.totalPage-2)+'</div>'+
                '<div pageno="'+(x.totalPage-1)+'">'+(x.totalPage-1)+'</div>'+
                '<div pageno="'+x.totalPage+'">'+x.totalPage+'</div>'
        }else{
            str = '<div pageno="1" style="color: '+(x.pageNo==1?"#1772fa":"")+'">1</div>'+
                '<div pageno="2" style="color: '+(x.pageNo==2?"#1772fa":"")+'">2</div>'+
                '<div pageno="3" style="color: '+(x.pageNo==3?"#1772fa":"")+'">3</div>'+
                '<div pageno="null">...</div>'+
                '<div pageno="'+(x.totalPage-2)+'" style="color: '+(x.pageNo==(x.totalPage-2)?"#1772fa":"")+'">'+(x.totalPage-2)+'</div>'+
                '<div pageno="'+(x.totalPage-1)+'" style="color: '+(x.pageNo==(x.totalPage-1)?"#1772fa":"")+'">'+(x.totalPage-1)+'</div>'+
                '<div pageno="'+x.totalPage+'" style="color: '+(x.pageNo==x.totalPage?"#1772fa":"")+'">'+x.totalPage+'</div>'
        }
    }
    $(y).empty().append(total_num+'<div class="paging_box">'+prve+str+next+'</div>')
}

$('body').on('click','.paging_box>div',function () {
    var pageno = $(this).attr('pageno');
    if(pageno!='null'){
        search_data.pageNo = pageno;
        get_search_res()
    }
})

function uploadImg_(fn) {
    s_loading();
    var formData = new FormData();
    var file = document.getElementById("file").files[0];
    if (!/\.(jpg|jpeg|png|JPG|PNG)$/.test(file.name)) {
        h_loading()
        s_warning('图片类型必须是jpeg,jpg,png中的一种')
        return false;
    }
    formData.append("file", file);
    $.ajax({
        url: ajax_url.updateAvatar,
        type: "POST",
        data: formData,
        processData: false,
        contentType: false,
        xhrFields: {
            withCredentials: true // 这里设置了withCredentials
        },
        // async: true,
        success: function (result) {
            console.log(result)
            h_loading()
            if(result.code == 200){
                if(result.data){
                    $('.photo2').css({
                        "background": "url("+result.data.image+")",
                        "background-size": "cover"
                    })
                }
            }
            else if(result.code==401){
                url_jump('login')
            }else{
                s_warning(response_status[result.code])
            }
        },
        error: function () {
            s_warning('上传失败')
        },
    })

}

$('.home_page').on('click',function () {
    url_jump('home')
})

$('.knowledge_page').on('click',function () {
    url_jump('knowledge')
})

$('.my_page').on('click',function () {
    url_jump('my')
});

function pro(option)
{

    return new Promise(function (a,b) {
        if(option.method=="post"){
            $.ajax({
                type: "POST",
                url: option.url,
                data: option.data,
                xhrFields: { withCredentials: true},
                success: function(result) {
                    a(result)
                },
                error: function(error) {
                    b(error)
                }
            });
        }else{
            $.ajax({
                type: "GET",
                url: option.url,
                xhrFields: {withCredentials: true },
                success: function(result) {
                    a(result)
                },
                error: function(error) {
                    b(error)
                }
            });
        }
    });
}

function pro_all(promise_arr,fn) {
    s_loading();
    return Promise.all(promise_arr).then(function (result) {
        h_loading()
        for(var i =0;i<result.length;i++){
            if(result[i].code == 200){
                fn[i](result[i].data)
            }
            else if(result[i].code==401){
                url_jump('login')
            }else if(result[i].code==403){
                url_jump('power')
            }else{
                s_warning(response_status[result[i].code])
            }
        }
    })
}

function option_structure(x) {
    var promise_arr = [];
    for(var i = 0;i<x.length;i++){
        promise_arr.push(pro(x[i]))
    }
    return promise_arr
}

function callback_structure(x) {
    var promise_arr = [];
    for(var i = 0;i<x.length;i++){
        promise_arr.push(x[i])
    }
    return promise_arr
}

function judge_data(res,fn){
    if(res&&res.length>0){
        fn(res)
    }else{
        s_warning('无数据')
    }
}

function GetQueryString(name) {
    var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)","i");
    var r = window.location.search.substr(1).match(reg);
    if (r!=null) return (r[2]); return null;
}

function deepClone(data){
    if(!data || !(data instanceof Object) || (typeof data=="function"))
    {
        return data||"";
    }
    var constructor = data.constructor;
    var result = new constructor();
    for(var key in data){
        if(data.hasOwnProperty(key)){
            result[key]=deepClone(data[key]);
        }
    }
    return result;
}

function getFileType (filePath){
    var startIndex = filePath.lastIndexOf(".");
    if(startIndex != -1)
        return filePath.substring(startIndex+1, filePath.length).toLowerCase();
    else return "";
}







